<template>
	<view class="favorites-container">
		<!-- 导航栏 -->
		<ob-navbar title="我的收藏" :show-back="true">
			<template #right>
				<text 
					v-if="favoriteList.length > 0"
					class="edit-btn"
					@click="toggleEditMode"
				>
					{{ isEditMode ? '完成' : '编辑' }}
				</text>
			</template>
		</ob-navbar>
		
		<!-- 收藏列表 -->
		<scroll-view 
			class="favorites-content" 
			scroll-y="true"
			@scrolltolower="loadMore"
			:lower-threshold="100"
		>
			<view v-if="favoriteList.length > 0" class="favorites-list">
				<view 
					v-for="item in favoriteList" 
					:key="item.favoriteId"
					class="favorite-item"
					:class="{ 'edit-mode': isEditMode }"
				>
					<!-- 选择框 -->
					<view 
						v-if="isEditMode" 
						class="select-box"
						@click="toggleSelect(item.favoriteId)"
					>
						<view class="checkbox" :class="{ checked: selectedItems.includes(item.favoriteId) }">
							<text v-if="selectedItems.includes(item.favoriteId)" class="check-icon">✓</text>
						</view>
					</view>
					
					<!-- 商品信息 -->
					<view class="product-info" @click="goToProductDetail(item.productId)">
						<!-- 商品图片 -->
						<image 
							class="product-image"
							:src="item.coverImage || '/static/images/default-product.png'"
							mode="aspectFill"
						/>
						
						<!-- 商品详情 -->
						<view class="product-details">
							<text class="product-name">{{ item.productName }}</text>
							<text class="product-desc">{{ item.description }}</text>
							<view class="product-meta">
								<text class="favorite-time">收藏时间：{{ formatDate(item.favoriteTime) }}</text>
								<text 
									class="product-status"
									:class="getStatusClass(item.status)"
								>
									{{ getStatusText(item.status) }}
								</text>
							</view>
						</view>
						
						<!-- 操作按钮 -->
						<view v-if="!isEditMode" class="product-actions">
							<button 
								class="action-btn remove"
								@click.stop="removeFavorite(item.favoriteId, item.productId)"
							>
								取消收藏
							</button>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<ob-empty 
				v-if="!isLoading && favoriteList.length === 0"
				image="/static/images/empty-favorite.png"
				text="暂无收藏"
				:show-button="true"
				button-text="去逛逛"
				@button-click="goToShopping"
			/>
			
			<!-- 加载更多 -->
			<view v-if="hasMore && favoriteList.length > 0" class="load-more">
				<text class="load-text">{{ isLoadingMore ? '加载中...' : '上拉加载更多' }}</text>
			</view>
			
			<view v-if="!hasMore && favoriteList.length > 0" class="no-more">
				<text class="no-more-text">没有更多收藏了</text>
			</view>
		</scroll-view>
		
		<!-- 批量操作底部栏 -->
		<view v-if="isEditMode" class="bottom-toolbar">
			<view class="toolbar-left">
				<view class="select-all" @click="toggleSelectAll">
					<view class="checkbox" :class="{ checked: isAllSelected }">
						<text v-if="isAllSelected" class="check-icon">✓</text>
					</view>
					<text class="select-text">全选</text>
				</view>
			</view>
			<view class="toolbar-right">
				<button 
					class="batch-btn remove"
					:disabled="selectedItems.length === 0"
					@click="batchRemoveFavorites"
				>
					删除 ({{ selectedItems.length }})
				</button>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import favoriteApi from '../../api/favorite.js'

// 响应式数据
const favoriteList = ref([])
const isLoading = ref(false)
const isLoadingMore = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const isEditMode = ref(false)
const selectedItems = ref([])

// 计算属性
const isAllSelected = computed(() => {
	return favoriteList.value.length > 0 && selectedItems.value.length === favoriteList.value.length
})

// 页面加载
onMounted(() => {
	loadFavoriteList()
})

// 加载收藏列表
const loadFavoriteList = async (reset = false) => {
	if (reset) {
		currentPage.value = 1
		hasMore.value = true
		favoriteList.value = []
	}
	
	if (!hasMore.value) return
	
	try {
		isLoading.value = reset
		isLoadingMore.value = !reset
		
		const params = {
			page: currentPage.value,
			size: pageSize.value
		}
		
		const result = await favoriteApi.getUserFavorites(params)
		
		if (result && result.success) {
			const newFavorites = result.data.favorites || []
			
			if (reset) {
				favoriteList.value = newFavorites
			} else {
				favoriteList.value.push(...newFavorites)
			}
			
			// 检查是否还有更多数据
			hasMore.value = result.data.current < result.data.pages
			
			if (hasMore.value) {
				currentPage.value++
			}
		}
	} catch (error) {
		console.error('加载收藏列表失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
		isLoadingMore.value = false
	}
}

// 加载更多
const loadMore = () => {
	if (!isLoadingMore.value && hasMore.value) {
		loadFavoriteList(false)
	}
}

// 切换编辑模式
const toggleEditMode = () => {
	isEditMode.value = !isEditMode.value
	if (!isEditMode.value) {
		selectedItems.value = []
	}
}

// 切换选择状态
const toggleSelect = (favoriteId) => {
	const index = selectedItems.value.indexOf(favoriteId)
	if (index > -1) {
		selectedItems.value.splice(index, 1)
	} else {
		selectedItems.value.push(favoriteId)
	}
}

// 切换全选
const toggleSelectAll = () => {
	if (isAllSelected.value) {
		selectedItems.value = []
	} else {
		selectedItems.value = favoriteList.value.map(item => item.favoriteId)
	}
}

// 取消收藏
const removeFavorite = async (favoriteId, productId) => {
	try {
		uni.showModal({
			title: '取消收藏',
			content: '确定要取消收藏这个商品吗？',
			success: async (res) => {
				if (res.confirm) {
					uni.showLoading({
						title: '处理中...'
					})
					
					const result = await favoriteApi.removeFromFavorites(productId)
					
					if (result && result.success) {
						// 从列表中移除
						const index = favoriteList.value.findIndex(item => item.favoriteId === favoriteId)
						if (index > -1) {
							favoriteList.value.splice(index, 1)
						}
						
						uni.showToast({
							title: '已取消收藏',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: '取消收藏失败',
							icon: 'none'
						})
					}
					
					uni.hideLoading()
				}
			}
		})
	} catch (error) {
		uni.hideLoading()
		console.error('取消收藏失败:', error)
		uni.showToast({
			title: '取消收藏失败',
			icon: 'none'
		})
	}
}

// 批量删除收藏
const batchRemoveFavorites = async () => {
	if (selectedItems.value.length === 0) return
	
	try {
		uni.showModal({
			title: '批量删除',
			content: `确定要删除这 ${selectedItems.value.length} 个收藏吗？`,
			success: async (res) => {
				if (res.confirm) {
					uni.showLoading({
						title: '处理中...'
					})
					
					// 获取要删除的商品ID列表
					const productIds = favoriteList.value
						.filter(item => selectedItems.value.includes(item.favoriteId))
						.map(item => item.productId)
					
					// 批量删除
					const promises = productIds.map(productId => 
						favoriteApi.removeFromFavorites(productId)
					)
					
					const results = await Promise.allSettled(promises)
					
					// 统计成功删除的数量
					const successCount = results.filter(result => 
						result.status === 'fulfilled' && result.value && result.value.success
					).length
					
					// 从列表中移除已删除的项目
					favoriteList.value = favoriteList.value.filter(item => 
						!selectedItems.value.includes(item.favoriteId)
					)
					
					// 清空选择
					selectedItems.value = []
					isEditMode.value = false
					
					uni.showToast({
						title: `成功删除 ${successCount} 个收藏`,
						icon: 'success'
					})
					
					uni.hideLoading()
				}
			}
		})
	} catch (error) {
		uni.hideLoading()
		console.error('批量删除收藏失败:', error)
		uni.showToast({
			title: '删除失败',
			icon: 'none'
		})
	}
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
	if (!isEditMode.value) {
		uni.navigateTo({
			url: `/pages/product/detail?id=${productId}`
		})
	}
}

// 去购物
const goToShopping = () => {
	uni.switchTab({
		url: '/pages/index/index'
	})
}

// 格式化日期
const formatDate = (dateString) => {
	if (!dateString) return ''
	try {
		const date = new Date(dateString)
		const month = date.getMonth() + 1
		const day = date.getDate()
		return `${month}月${day}日`
	} catch (error) {
		return ''
	}
}

// 获取状态样式类
const getStatusClass = (status) => {
	switch (status) {
		case 'available':
			return 'status-available'
		case 'out_of_stock':
			return 'status-out-stock'
		case 'discontinued':
			return 'status-discontinued'
		default:
			return 'status-unknown'
	}
}

// 获取状态文本
const getStatusText = (status) => {
	switch (status) {
		case 'available':
			return '有库存'
		case 'out_of_stock':
			return '缺货'
		case 'discontinued':
			return '已下架'
		default:
			return '未知状态'
	}
}
</script>

<style lang="scss" scoped>
.favorites-container {
	min-height: 100vh;
	background: #F5F5F5;
}

.edit-btn {
	color: var(--primary-color);
	font-size: 16px;
}

.favorites-content {
	flex: 1;
	padding-bottom: 120px; // 为底部工具栏留空间
}

.favorites-list {
	padding: 15px;
}

.favorite-item {
	background: #FFFFFF;
	border-radius: 12px;
	margin-bottom: 15px;
	overflow: hidden;
	display: flex;
	align-items: center;
	padding: 15px;
	
	&.edit-mode {
		padding-left: 50px;
	}
}

.select-box {
	position: absolute;
	left: 15px;
	z-index: 10;
}

.checkbox {
	width: 20px;
	height: 20px;
	border: 2px solid #E0E0E0;
	border-radius: 10px;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&.checked {
		background: var(--primary-color);
		border-color: var(--primary-color);
	}
}

.check-icon {
	font-size: 12px;
	color: #FFFFFF;
}

.product-info {
	flex: 1;
	display: flex;
}

.product-image {
	width: 80px;
	height: 80px;
	border-radius: 8px;
	margin-right: 15px;
}

.product-details {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
	margin-bottom: 5px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.product-desc {
	font-size: 14px;
	color: #666666;
	margin-bottom: 10px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.product-meta {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.favorite-time {
	font-size: 12px;
	color: #999999;
}

.product-status {
	font-size: 12px;
	padding: 2px 8px;
	border-radius: 4px;
	
	&.status-available {
		background: #E8F5E8;
		color: #4CAF50;
	}
	
	&.status-out-stock {
		background: #FFF3E0;
		color: #FF9800;
	}
	
	&.status-discontinued {
		background: #FFEBEE;
		color: #F44336;
	}
	
	&.status-unknown {
		background: #F5F5F5;
		color: #999999;
	}
}

.product-actions {
	margin-left: 15px;
}

.action-btn {
	padding: 8px 15px;
	border: none;
	border-radius: 6px;
	font-size: 14px;
	
	&.remove {
		background: #FFEBEE;
		color: #F44336;
	}
}

.load-more, .no-more {
	text-align: center;
	padding: 20px;
}

.load-text, .no-more-text {
	font-size: 14px;
	color: #999999;
}

.bottom-toolbar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #FFFFFF;
	border-top: 1px solid #E0E0E0;
	padding: 15px 20px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	z-index: 100;
}

.toolbar-left {
	display: flex;
	align-items: center;
}

.select-all {
	display: flex;
	align-items: center;
}

.select-text {
	font-size: 16px;
	color: #333333;
	margin-left: 8px;
}

.batch-btn {
	padding: 10px 20px;
	border: none;
	border-radius: 6px;
	font-size: 16px;
	
	&.remove {
		background: #F44336;
		color: #FFFFFF;
	}
	
	&:disabled {
		background: #CCCCCC;
		color: #999999;
	}
}
</style>